/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import MouseSensorDriver.Calibrator;
import MouseSensorDriver.GraphListener;
import adc_lcard.ADCE140Driver;
import dynamixel.Actuator;
import dynamixel.EndoscopeGear;
import dynamixel.HostActuator;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.Timer;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import jssc.SerialPortList;

/**
 *
 * @author Asko
 */
public class ModernEndoscopFrame extends javax.swing.JFrame implements
        GraphListener {

    ArrayList<Double> engList = new ArrayList<>();
    ArrayList<Double> timeList = new ArrayList<Double>();
    ArrayList<GraphListener> glist = new ArrayList<>();
    ModernEndoscopFrame mf ;
    double curGraphValEng = 0;
    final int TIMER_PERIOD = 500;
    int iter = 0;
    double curGraphValAdc = 0;
    boolean newData = false;
    String strBuf = "";
    HostActuator actuatorHost;
    int currentEngine = 0;
    String[] portList = SerialPortList.getPortNames();
    DefaultComboBoxModel<String> dynamixelModel = new DefaultComboBoxModel<>();
    final int actCnt = 4;
    final int MAX_DIGS_CNT = 3;
    final int MIN_DIGS_CNT = 0;
    Actuator[] actuators = new Actuator[actCnt];
    EndoscopeGear[] gears = new EndoscopeGear[actCnt];
    EndoscopeChannel[] eChannels = new EndoscopeChannel[actCnt];
    EndoscopeExpContainer expContainer = new EndoscopeExpContainer();
    NumberFormat nform = NumberFormat.getInstance();
    ScriptAnalyzer analyzer;
    final String projectDirectory = "." + File.separator ;
    File curFile = new File(projectDirectory);
    //double maxPos[] = {43.01, 22.2657, 29.87, 150};
    //double minPos[] = {-36.65, -21.68, -31.65, 0};
    double maxPos[] = {45.1, 60.1, 165.1, 150.1};
    double minPos[] = {-45.1, -60.1, -45.1, 0};
    String[] nameUnitsPos = {"Grad", "Grad", "Grad", "mm"};
    String[] nameUnitsTorque = {"N*m", "N*m", "N*m", "N"};
    int[] adcChannelNums = {13, 12, 14, 15};
    int[] adcChannelNumsOS = {30, 31, 32, 33};
    int baudRate = 57142;
    int sI = 0;
    int it = 0;
    final int ARR_SIZE = 4096;
    double engArr[] = new double[ARR_SIZE];
    double times[] = new double[ARR_SIZE];
    GraphObserver go = new GraphObserver();
    Thread scan = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                if (newData) {
                    int len = iter;
                    double[] bufEng = new double[len];
                    double[] bufTime = new double[len];
                    System.arraycopy(times, 0, bufTime, 0, len);
                    System.arraycopy(engArr, 0, bufEng, 0, len);

                    panel.removeAllPlots();
                    panel.addLinePlot("", Color.RED, bufTime, bufEng);
                    // panel.repaint();

                    newData = false;
                }
                try {
                    Thread.sleep(TIMER_PERIOD);
                } catch (InterruptedException ex) {
                    Logger.getLogger(WardrobeFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });

    public boolean getStatus() {
        return newData;
    }
    Timer timer = new Timer(TIMER_PERIOD, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Timer ...");
            panel.addLinePlot("", Color.RED, times, engArr);
            panel.repaint();
        }
    });
    TableModelListener tablelistener = new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            if (expContainer != null) {
                double buf = expContainer.getSigma();
                if (buf == -1) {
                    jl_sko.setText("none");
                } else {
                    jl_sko.setText("" + nform.format(buf));
                }
                buf = expContainer.getMaxAbsError();
                if (buf == -1) {
                    jl_maxe.setText("none");
                } else {
                    jl_maxe.setText("" + nform.format(buf));
                }
            }
        }
    };

    /**
     * Creates new form EndoscopFrame
     */
    public ModernEndoscopFrame() {
        for (int i = 0; i < portList.length; i++) {
            dynamixelModel.addElement(portList[i]);
        }
        if (!ADCE140Driver.init()) {
            System.out.println("ADC failed  to initialize. Try again or reboot.");
            System.exit(1);
        }
        actuatorHost = new HostActuator(baudRate);
        for (int i = 0; i < actCnt; i++) {
            actuators[i] = new Actuator(actuatorHost, i + 1);
            gears[i] = new EndoscopeGear(actuators[i], nameUnitsPos[i],
                    nameUnitsTorque[i], maxPos[i], minPos[i]);
            eChannels[i] = new EndoscopeChannel(gears[i], adcChannelNums[i],
                    Calibrator.ES_ADC_CHANELL_1 + i,
                    Calibrator.ES_TOR_ADC_CHANELL_1 + i);
        }
        analyzer = new ScriptAnalyzer("", expContainer, eChannels);
//        timer.start();
        System.out.println("Init done");
        nform.setMaximumFractionDigits(MAX_DIGS_CNT);
        nform.setMinimumFractionDigits(MIN_DIGS_CNT);
        initComponents();

//        timer.start();
        expContainer.addTableModelListener(tablelistener);
        scan.start();
        glist.add(this);
        mf = this ;
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        j_popup = new javax.swing.JPopupMenu();
        j_menu_item = new javax.swing.JMenuItem();
        jPanel5 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        j_cb2 = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();
        j_tf1 = new javax.swing.JTextField();
        j_label_units_name_1 = new javax.swing.JLabel();
        J_b_load = new javax.swing.JButton();
        J_b_save = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jPanel13 = new javax.swing.JPanel();
        jButton7 = new javax.swing.JButton();
        j_button_delete_row = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        j_button_to_graph_pos = new javax.swing.JButton();
        jtb_post = new javax.swing.JToggleButton();
        j_button_torq = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        j_text_area = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jl_sko = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jl_maxe = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        panel = new org.math.plot.Plot2DPanel();

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        j_menu_item.setText("Открыть сценарий");
        j_menu_item.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                j_menu_itemActionPerformed(evt);
            }
        });
        j_popup.add(j_menu_item);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel2.setText("Actuator");

        j_cb2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Поперечное вращение", "Вращение вокруг оси", "Продольное вращение", "Поступательное движениe" }));
        j_cb2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                j_cb2ActionPerformed(evt);
            }
        });

        jButton2.setText("GoToPos");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        j_label_units_name_1.setText("mm");

        J_b_load.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Load.png"))); // NOI18N
        J_b_load.setToolTipText("Load experiments");
        J_b_load.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                J_b_loadActionPerformed(evt);
            }
        });

        J_b_save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Save-iconSmall.png"))); // NOI18N
        J_b_save.setToolTipText("Save experiments");
        J_b_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                J_b_saveActionPerformed(evt);
            }
        });

        jButton1.setText("Load");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Save");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(j_cb2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(j_tf1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(j_label_units_name_1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addGap(24, 24, 24)
                .addComponent(J_b_save, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(J_b_load, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(J_b_save, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(J_b_load, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton2)
                        .addComponent(j_tf1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(j_label_units_name_1)
                        .addComponent(jButton1)
                        .addComponent(jButton3))
                    .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(j_cb2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton7.setBackground(new java.awt.Color(238, 0, 0));
        jButton7.setText("RemoveAll");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        j_button_delete_row.setBackground(new java.awt.Color(238, 0, 0));
        j_button_delete_row.setText("DeleteRow");
        j_button_delete_row.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                j_button_delete_rowActionPerformed(evt);
            }
        });

        jButton4.setText("Export");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("DoScript");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("ViewObserver");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        j_button_to_graph_pos.setText("toGraphPos");
        j_button_to_graph_pos.setEnabled(false);
        j_button_to_graph_pos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                j_button_to_graph_posActionPerformed(evt);
            }
        });

        jtb_post.setSelected(true);
        jtb_post.setText("Post");

        j_button_torq.setText("toGraphTor");
        j_button_torq.setEnabled(false);
        j_button_torq.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                j_button_torqActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
        jPanel13.setLayout(jPanel13Layout);
        jPanel13Layout.setHorizontalGroup(
            jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel13Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel13Layout.createSequentialGroup()
                        .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(j_button_delete_row))
                    .addGroup(jPanel13Layout.createSequentialGroup()
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton6))
                    .addGroup(jPanel13Layout.createSequentialGroup()
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtb_post, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(j_button_torq, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(j_button_to_graph_pos, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel13Layout.setVerticalGroup(
            jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel13Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton5)
                    .addComponent(jButton6))
                .addGap(14, 14, 14)
                .addComponent(j_button_to_graph_pos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(j_button_torq)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jtb_post))
                .addGap(39, 39, 39)
                .addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton7)
                    .addComponent(j_button_delete_row))
                .addContainerGap())
        );

        j_text_area.setColumns(20);
        j_text_area.setRows(5);
        j_text_area.setComponentPopupMenu(j_popup);
        jScrollPane2.setViewportView(j_text_area);

        jTable1.setModel(expContainer);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel1.setText("Sigma:");

        jl_sko.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jl_sko.setForeground(new java.awt.Color(234, 0, 0));
        jl_sko.setText("none");

        jLabel4.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel4.setText("Max error:");

        jl_maxe.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jl_maxe.setForeground(new java.awt.Color(229, 0, 0));
        jl_maxe.setText("none");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jl_sko)
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jl_maxe)
                .addContainerGap(817, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jl_sko)
                    .addComponent(jLabel4)
                    .addComponent(jl_maxe))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1050, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 4, Short.MAX_VALUE))
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int selIndx = j_cb2.getSelectedIndex();
        if (selIndx != -1) {
            gears[selIndx].setPosition(Double.valueOf(j_tf1.getText()));
//            actuators[j_cb2.getSelectedIndex()].setGoalPosition(Integer.
//                    valueOf(j_tf1.getText()));
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void j_cb2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j_cb2ActionPerformed
        int selIndx = j_cb2.getSelectedIndex();
        if (selIndx != -1) {

            //System.out.println("Selected indx: " + selIndx);
            j_label_units_name_1.setText("" + gears[selIndx].getUnitPosition());
            currentEngine = selIndx;
        }

    }//GEN-LAST:event_j_cb2ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        int sel = jTable1.getSelectedRow();
        if (sel != -1) {
            if (expContainer.get(sel).getSize() > 0) {
                j_button_torq.setEnabled(true);
                j_button_to_graph_pos.setEnabled(true);
            } else {
                j_button_to_graph_pos.setEnabled(false);
                j_button_torq.setEnabled(false);
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked

    private void j_menu_itemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j_menu_itemActionPerformed
        JFileChooser jf = new JFileChooser();
        jf.setCurrentDirectory(curFile);
        int res = jf.showOpenDialog(this);
        if (res == JFileChooser.APPROVE_OPTION) {
            try {
                FileInputStream fis = new FileInputStream(jf.getSelectedFile());
                String buf = "";
                while ((res = fis.read()) != -1) {
                    buf += (char) res;
                }
                fis.close();
                j_text_area.setText(buf);
            } catch (IOException ex) {
                Logger.getLogger(ModernEndoscopFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_j_menu_itemActionPerformed

    private void j_button_to_graph_posActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j_button_to_graph_posActionPerformed
        go.removeAllPlots();
        int sel = jTable1.getSelectedRow();
        if (sel > -1) {
            if (expContainer.get(sel).getSize() > 0) {
                go.addPlot("Позиция двигателя", expContainer.get(sel).getTime(),
                        expContainer.get(sel).getPosEng());
                go.addPlot("Позиция АЦП", expContainer.get(sel).getTime(),
                        expContainer.get(sel).getPosAdc());
            }
        }
    }//GEN-LAST:event_j_button_to_graph_posActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        go.setVisible(true);
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        iter = 0;
        new Thread(new Runnable() {
            @Override
            public void run() {
                analyzer.setSource(j_text_area.getText());
                analyzer.setAirship(jtb_post.isSelected());
                analyzer.addScanListener(mf);
                analyzer.startAnalyze();
            }
        }).start();

    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        JFileChooser fc = new JFileChooser("Выберите файл для сохранения");
        fc.setDialogType(JFileChooser.SAVE_DIALOG);
        fc.setCurrentDirectory(curFile);
        int res = fc.showSaveDialog(this);
        if (res == JFileChooser.APPROVE_OPTION) {
            try {
                File file = fc.getSelectedFile().getAbsolutePath().contains(".")
                        ? fc.getSelectedFile() : new File(fc.getSelectedFile().
                        getAbsolutePath() + ".csv");
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(expContainer.getCSV().getBytes("windows-1251"));
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(ControlFrrame.class.getName()).
                        log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void j_button_delete_rowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j_button_delete_rowActionPerformed
        int r = jTable1.getSelectedRow();
        //   System.out.println("Selected row -> " +  r);
        if (r != -1) {
            //System.out.println("getSelectedRow "+jTable1.getSelectedRow()+" col1"+jTable1.getSelectedColumns()[0]);
            if (jTable1.getSelectedColumnCount() > 1) {
                int ind = jTable1.getSelectedRow();
                int cnt_del = jTable1.getSelectedRowCount();
                for (int i = 0; i < cnt_del; i++) {
                    expContainer.remove(ind);
                }
            } else {
                expContainer.remove(r);
            }
        }
    }//GEN-LAST:event_j_button_delete_rowActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        expContainer.removeAll();
    }//GEN-LAST:event_jButton7ActionPerformed

    private void J_b_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_J_b_saveActionPerformed
        JFileChooser fc = new JFileChooser();
        if (curFile.exists()) {
            fc.setCurrentDirectory(curFile);
        }
        if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            if (expContainer != null) {
                expContainer.saveToFile(fc.getSelectedFile());
            } else {
                System.err.println("Failed to save data. ExpContainer is null");
            }
        }
    }//GEN-LAST:event_J_b_saveActionPerformed

    private void J_b_loadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_J_b_loadActionPerformed
        JFileChooser fc = new JFileChooser();
        if (curFile.exists()) {
            fc.setCurrentDirectory(curFile);
        }
        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            expContainer.loadFromFile(fc.getSelectedFile());
        }
    }//GEN-LAST:event_J_b_loadActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser fc = new JFileChooser();
        if (curFile.exists()) {
            fc.setCurrentDirectory(curFile);
        }
        if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                FileInputStream fis = new FileInputStream(fc.getSelectedFile());
                BufferedInputStream bis = new BufferedInputStream(fis);

                int buf = 0;
                String sbuf = "";
                try {
                    while ((buf = bis.read()) != -1) {
                        sbuf += (char) buf;
                    }
                    bis.close();
                    fis.close();
                    j_text_area.setText(sbuf);
                } catch (IOException ex) {
                    Logger.getLogger(ModernEndoscopFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ModernEndoscopFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        JFileChooser fc = new JFileChooser();
        if (curFile.exists()) {
            fc.setCurrentDirectory(curFile);
        }
        if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                FileOutputStream fos = new FileOutputStream(fc.getSelectedFile());
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                try {
                    bos.write(j_text_area.getText().getBytes());
                    bos.close();
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(ModernEndoscopFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ModernEndoscopFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void j_button_torqActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_j_button_torqActionPerformed

        go.removeAllPlots();
        int sel = jTable1.getSelectedRow();
        if (sel > -1) {
            if (expContainer.get(sel).getSize() > 0) {
                go.addPlot("Момент двигателя", expContainer.get(sel).getTime(),
                        expContainer.get(sel).getTorEng());
                go.addPlot("Момент АЦП", expContainer.get(sel).getTime(),
                        expContainer.get(sel).getTorAdc());
            }
        }// TODO add your handling code here:


    }//GEN-LAST:event_j_button_torqActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ModernEndoscopFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ModernEndoscopFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ModernEndoscopFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ModernEndoscopFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ModernEndoscopFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton J_b_load;
    private javax.swing.JButton J_b_save;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton j_button_delete_row;
    private javax.swing.JButton j_button_to_graph_pos;
    private javax.swing.JButton j_button_torq;
    private javax.swing.JComboBox j_cb2;
    private javax.swing.JLabel j_label_units_name_1;
    private javax.swing.JMenuItem j_menu_item;
    private javax.swing.JPopupMenu j_popup;
    private javax.swing.JTextArea j_text_area;
    private javax.swing.JTextField j_tf1;
    private javax.swing.JLabel jl_maxe;
    private javax.swing.JLabel jl_sko;
    private javax.swing.JToggleButton jtb_post;
    private org.math.plot.Plot2DPanel panel;
    // End of variables declaration//GEN-END:variables

    @Override
    public void addValue(double eng, double time) {
        if (iter < ARR_SIZE) {
            engArr[iter] = eng;
            times[iter] = time;
            if (iter == 1) {
                engArr[0] = eng;
                times[0] = time;
            }
            iter++;
            newData = true;
        } else {
            System.err.println("Reached end of array");
        }
    }
    
    @Override
    public void clear() {
        iter = 1;
    }
}
